package com.ssm.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssm.bean.Device;
import com.ssm.service.DeviceService;

/**
 * @author ZhaoXianming
 * @Description 设备管理
 * @date 2020年3月12日
 */
@Controller
@RequestMapping("/deviceManagement")
public class DeviceManagementController {
	
	Logger log = LoggerFactory.getLogger(DeviceManagementController.class);
	
	@Autowired
	private DeviceService deviceService;

	@RequestMapping("/toDeviceJsp")
	public String toDeviceManagementJsp(){
		return "deviceManagement/deviceList";
	}
	
	@RequestMapping(value = "/getDevices/{pageNo}/{pageSize}")
	@ResponseBody
	public Map<String,Object> getDevices(@PathVariable int pageNo, @PathVariable int pageSize,
			@RequestBody Device device, HttpServletRequest request) {
		Map<String,Object> params = new HashMap<>();
		params.put("pageNo", pageNo);
		params.put("pageSize", pageSize);
		params.put("device", device);
		int cnt = deviceService.getDevicesCnt(params);
		if(cnt > 0){
			params.put("totalPage", (int)Math.ceil((double)cnt/10));
			params.put("totalRecord", cnt);
			List<Device> list = deviceService.getDevices(params);
			params.put("deviceList", list);
			return params;
		}
		return Collections.emptyMap();
	}
	
	@RequestMapping("/toAddDeviceJsp")
	public String toAddJsp(){
		return "deviceManagement/deviceAdd";
	}
	
	@RequestMapping("/toUpdateDeviceJsp")
	public String toUpdateJsp(HttpServletRequest request, Model model, String ipAddress){
		Device device = deviceService.getDeviceByIp(ipAddress);
		model.addAttribute("device",device);
		return "deviceManagement/deviceUpdate";
	}
	
	@RequestMapping("/isDeviceRepeated")
	@ResponseBody
	public boolean isDeviceRepeated(String ipAddress){
		int row = deviceService.isRepeated(ipAddress);
		return row > 0?false:true;
	}
	
	@RequestMapping("/addOrUpdateDevice")
	@ResponseBody
	public String addOrUpdate(@RequestBody Device device){
		try{
			deviceService.insertDevice(device);
			return "success";
		}catch(Exception e){
			log.error("添加设备出错了", e);
			return "error";
		}
	}
	
	@RequestMapping("/deleteDevices")
	@ResponseBody
	public void deleteDevices(@RequestParam List<String> ipAddress){
		deviceService.deleteDevices(ipAddress);
	}
}
